// ==UserScript==
// @name         山大图书馆数据获取脚本
// @version      0.1
// @description  try to take over the world!
// @author       严一涵
// @include      http://58.194.172.34/opac/item.php*
// @grant        none
// ==/UserScript==

(() => {
    interface BookType {
        id: string;
        title: string;
        author: string;
        publisher: string;
        publicationDate: string;
        price: string;
        category: string;
        totalQuantity: string;
        currentQuantity: string;
    }
    let book: BookType = {
        id: '',
        title: '',
        author: '',
        publisher: '',
        publicationDate: '',
        price: '',
        category: '',
        totalQuantity: '',
        currentQuantity: ''
    };
    let item_detail = document.querySelector<HTMLDivElement>('div#item_detail');
    if (!item_detail) {
        console.log('资源读取失败');
        return;
    }
    let dlList = item_detail.querySelectorAll('dl');
    dlList.forEach(dl => {
        let dt = dl.querySelector('dt');
        let dd = dl.querySelector('dd');
        if (dt && dt.textContent && dd && dd.textContent) {
            let key = dt.textContent;
            let value = dd.textContent;
            if (key.includes('题名/责任者')) {
                let splitStr = value.split('/');
                book.title = splitStr[0];
                book.author = splitStr[1];
            } else if (key.includes('出版发行项')) {
                let splitStr = value.split(',');
                book.publisher = splitStr[0];
                book.publicationDate = splitStr[1];
            } else if (key.includes('ISBN及定价')) {
                let splitStr = value.split('/');
                book.id = splitStr[0];
                book.price = splitStr[1].split('').filter(v => v >= '0' && v <= '9' || v == '.').join('');
            } else if (key.includes('中图法分类号')) {
                book.category = value;
            }
        }
    });
    let item = document.querySelector<HTMLTableElement>('table#item');
    if (item) {
        let count = item.querySelectorAll('tr.whitetext').length;
        book.totalQuantity = `${count}`;
        book.currentQuantity = `${count}`;
    }
    let CSVStr = (str: string) => {
        return '\"' + str.split('\"').join('\"\"') + '\"';
    };
    let ansList = Array<string>();
    ansList.push(CSVStr(book.id));
    ansList.push(CSVStr(book.title));
    ansList.push(CSVStr(book.author));
    ansList.push(CSVStr(book.publisher));
    ansList.push(CSVStr(book.publicationDate));
    ansList.push(CSVStr(book.price));
    ansList.push(CSVStr(book.category));
    ansList.push(CSVStr(book.totalQuantity));
    ansList.push(CSVStr(book.currentQuantity));
    let ans = ansList.join(',');
    console.log(ans);
    let p = document.createElement('p');
    p.textContent = ans;
    item_detail.insertBefore(p, item_detail.firstChild);
})();
